import router from '@/router'
import store from '@/store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import defaultSettings from '@/utils/get-page-title'
import { asyncRoutes } from '@/router'

const whiteList = ['/login', '/404']

// 权限管理 全局导航守卫
router.beforeEach(async(to, form, next) => {
  document.title = defaultSettings(to.meta.title)
  const token = store.state.user.token
  NProgress.start()
  if (token) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      if (!store.state.user.userInfo.username) {
        const menus = await store.dispatch('user/userInfo')
        // 获取权限信息
        console.log(menus, '权限权限你')
        const filterRoutes = asyncRoutes.filter(item => {
          return menus.includes(item.children[0].name)
        })
        console.log(filterRoutes, 'filterRoutes')
        router.addRoutes(filterRoutes)
        // 存到Vuex
        store.commit('menus/setMenusList', filterRoutes)
        next({ ...to, replace: true })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})

